﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;
using SCSEngine.ScreenManagement.Implement;
using SCSEngine.ScreenManagement;
using SCSEngine.Services;
using SCSEngine.ResourceManagement;
using TriUan.SCSEngine.Utils;
using TriUan.TriUanGameComponent.GameComponents;
using TriUan.TriUanGame.GameComponents.Polygon;
using TriUan.TriUanGame.GameComponents.Polygon.Implements;
using TriUan.TriUanGame.GameComponents;
using Microsoft.Xna.Framework.Input.Touch;
using SCSEngine.Services.Input;
using SCSEngine.Control;
using SCSEngine.Sprite;
using SVLvsXNA.Facebook;
using Microsoft.Xna.Framework.Input;


namespace TriUan.TriUanGame.GameScreen
{
    class ClassicGameModeScreen : BaseGameScreen
    {
        private SCSServices engine = null;
        private IResourceManager resourceManager;

        private Texture2D _background = null;

        private PiecesManager _piecesMgr;
        private Pattern pattern;

        private Camera2D _camera;
        private InputHandle inputHandle;
        Button buttonPost = null;
        private bool IsWin = false;
        private SpriteFont font;

        public ClassicGameModeScreen(IGameScreenManager manager, string patternStr)
            : base(manager)
        {
            engine = (SCSServices)manager.GamePage.Services.GetService(typeof(SCSServices));
            resourceManager = (IResourceManager)manager.GamePage.Services.GetService(typeof(IResourceManager));

            TouchPanel.EnabledGestures = GestureType.Tap | GestureType.FreeDrag | GestureType.Hold;
            // Load content
            _piecesMgr = new PiecesManager(engine, resourceManager);

            // Pattern
            pattern = loadPattern("Pattern/" + patternStr, "patternXml\\" + patternStr + ".xml");

            font = resourceManager.GetResource<SpriteFont>("TitleFont");

            _camera = new Camera2D(800,
                    480, 800, 960, 1.0f);

            Camera2D.Pos = new Vector2(0, -220);

            _background = resourceManager.GetResource<Texture2D>("TriUan_GamePlay1");

            //if (buttonPost == null)
            //{
            //    buttonPost = new Button(this.GamePage, resourceManager.GetResource<ISprite>("share"));
            //    buttonPost.Size = new Vector2(122f, 42f);
            //    buttonPost.Position = new Vector2(650f, 300f);
            //    buttonPost.OnTouched += new OnButtonTouchedHandler(buttonPost_OnTouched);
            //    buttonPost.Visible = buttonPost.Enabled = true;
            //    Components.Add(buttonPost);
            //}

            inputHandle = engine.InputHandle;
        }


        private Pattern loadPattern(string fileTexture, string fileXml)
        {
            Pattern pattern;
            TUPolygon poligon;
            TUPolygonInfo pieceInfo;
            Texture2D texture = resourceManager.GetResource<Texture2D>(fileTexture);
            List<Vector2> listVerts = new List<Vector2>();
            Vector2 orig;


            XMLReader xml = new XMLReader(fileXml);
            XPoint xpoint = xml.ReadFile();
            orig = xml.GetCenter();

            foreach (Vector2 item in xpoint.mListOfVector)
            {
                listVerts.Add(item);
            }

            poligon = new TUPolygon(listVerts, orig);
            Random rand = new Random();
            pieceInfo = new TUPolygonInfo(1f, new Vector2(371, 435f));//15f, 21f

            pattern = new Pattern(engine.GamePage, poligon, pieceInfo, texture);
            pattern.Scale = 0.7f;
            return pattern;
        }

        public override void Update(GameTime gameTime)
        {
            if (this.GamePage.IsBackKeyPress)
            {
                Manager.RemoveCurrent();
                Manager.AddExclusive(Manager.Bank.GetScreen("Menu"));
                this.GamePage.IsBackKeyPress = false;
            }

            pattern.Update(gameTime);
            if (!_piecesMgr.UpdateSpieces(gameTime))
                HandleInput();
            CheckWinFun();

            if (buttonPost != null)
                buttonPost.Update(gameTime);

            base.Update(gameTime);
            
        }

        private void HandleInput()
        {
            foreach (GestureSample sample in inputHandle.Gestures)
            {
                float sc = 1;
                if (sample.GestureType == GestureType.FreeDrag)
                {
                    _camera.Move(sample.Delta);
                }

                if (sample.GestureType == GestureType.Pinch)
                {
                    sc = Camera2D.Scale(sample.Position, sample.Position2, sample.Delta, sample.Delta2);
                    Camera2D.Zoom *= sc;
                }
            }
        }

        public override void Draw(GameTime gameTime)
        {
            engine.SpriteBatch.End();
            engine.SpriteBatch.Begin(SpriteSortMode.Deferred, BlendState.AlphaBlend, null, null, null, null, _camera.GetTransformation());

            engine.SpriteBatch.Draw(_background, Vector2.Zero, Color.White);
            
            pattern.Draw(gameTime);
            List<Piece> pieces = _piecesMgr.Pices;
            foreach (Piece item in pieces)
            {
                item.Draw(gameTime);
            }
            engine.SpriteBatch.DrawString(font, IsWin ? "Win" : "...", new Vector2(651f, 401f), Color.White);
            engine.SpriteBatch.DrawString(font, IsWin ? "Win" : "...", new Vector2(650f, 400f), Color.Green);

            if (buttonPost != null)
                buttonPost.Draw(gameTime);
            base.Draw(gameTime);
        }

        private float minDist = 30;

        public void CheckWinFun()
        {
            Dictionary<ITUPolygon, ITUPieceInfo> list = new Dictionary<ITUPolygon, ITUPieceInfo>();
            foreach (var item in _piecesMgr.Pices)
            {
                list.Add(item.Vertices, item.PieceInfo);
            }
            if (CheckWin.Instance().IsCompleted(pattern.Polygon, pattern.PolygonInfo, list, minDist))
            {
                IsWin = true;
                if (buttonPost == null)
                {
                    buttonPost = new Button(this.GamePage, resourceManager.GetResource<ISprite>("share"));
                    buttonPost.Size = new Vector2(122f, 42f);
                    buttonPost.Position = new Vector2(650f, 300f);
                    buttonPost.OnTouched += new OnButtonTouchedHandler(buttonPost_OnTouched);
                    buttonPost.Visible = buttonPost.Enabled = true;
                    Components.Add(buttonPost);
                }
            }
            else
                IsWin = false;
        }

        void buttonPost_OnTouched(Button sender, EventArgs args)
        {
            var par = new Dictionary<string, object>();
            par.Add("picture", "http://uit-scsgroup.info/forum/images/banner/logo.png");
            par.Add("link", "http://apps.facebook.com/xephinhapp/");
            par.Add("name", "Mình vừa giải được hình này trên Trí Uẩn. Đố mọi người giải được :D");
            par.Add("caption", "Trí Uẩn game");
            par.Add("description", "Mình vừa chơi Trí Uẩn trên windows phone. Đã giải được hình này");

            FacebookServices.GetInstanse().PostAsync("me/feed", par, (o, ex) =>
            {
                if (ex.Error != null)
                {
                    return;
                }
            });
        }
    }
}
